package com.shop.cereshop.app.dl.logic.service.Impl;

import com.shop.cereshop.app.dao.buyer.CereBuyerWithdrawalDAO;
import com.shop.cereshop.app.dao.distributor.CereDistributionOrderDAO;
import com.shop.cereshop.app.dao.distributor.CereShopDistributorDAO;
import com.shop.cereshop.app.dao.dl.CereBuyerUserDao;
import com.shop.cereshop.app.dao.dl.CerePlatformUserPointDao;
import com.shop.cereshop.app.dao.dl.CereShopProductMapper;
import com.shop.cereshop.app.dao.order.CereShopOrderDAO;
import com.shop.cereshop.app.dl.logic.domian.CereBuyerUser;
import com.shop.cereshop.app.dl.logic.domian.MyAccount;
import com.shop.cereshop.app.dl.logic.service.DlCereBuyerUserService;
import com.shop.cereshop.app.dl.logic.utils.WeixinUtil;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.utils.GZHUtil;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EncryptUtil;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: 况鑫威
 * @Date: 2021/6/15
 * @Time: 17:51
 * @ClassName: DlCereBuyerUserServiceImpl
 * @Description: com.shop.cereshop.app.dl.logic.service.serviceImpl
 */
@Service
public class DlCereBuyerUserServiceImpl implements DlCereBuyerUserService {
    @Value("${Dl_Message.shopId}")
    private Long shopId;
    @Value("${Dl_Message.grade}")
    private Long grade;
    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.expire_seconds}")
    private Integer expire_seconds;

    @Value("${weixin.secret}")
    private String secret;

    @Autowired
    private CereBuyerUserDao cereBuyerUserDao;
    @Autowired
    private CereBuyerWithdrawalDAO cereBuyerWithdrawalDAO;
    @Autowired
    private StringRedisService stringRedisService;
    @Autowired
    private CereShopDistributorDAO cereShopDistributorDAO;
    @Autowired
    private CerePlatformUserPointDao cerePlatformUserPointDao;
    @Autowired
    private CereDistributionOrderDAO cereDistributionOrderDAO;
    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;
    @Autowired
    private CereShopProductMapper cereShopProductMapper;

    @Override
    public int deleteByPrimaryKey(Long buyerUserId) {
        return cereBuyerUserDao.deleteByPrimaryKey(buyerUserId);
    }

    @Override
    public int insert(CereBuyerUser record) {
        return cereBuyerUserDao.insert(record);
    }

    @Override
    public int insertSelective(CereBuyerUser record) {
        return cereBuyerUserDao.insertSelective(record);
    }

    @Override
    public CereBuyerUser selectByPrimaryKey(Long buyerUserId) {
        return cereBuyerUserDao.selectByPrimaryKey(buyerUserId);
    }

    @Override
    public int updateByPrimaryKeySelective(CereBuyerUser record) {
        return cereBuyerUserDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(CereBuyerUser record) {
        return cereBuyerUserDao.updateByPrimaryKey(record);
    }

    @Override
    public Boolean phoneBinding(String wechatOpenId, String phone, String code) {
        //判断是否为空
        if (code == null || "".equals(code)) {
            return false;
        }
        if (phone == null || "".equals(phone)) {
            return false;
        }
        //手机验证码验证
        String phoneCode = (String) stringRedisService.get(phone);
        if (!code.equals(phoneCode)) {
            return false;
        }

//        //查询替换值
//        List<CereBuyerUser> cereBuyerUser = cereBuyerUserDao.getByWxOpenId(wechatOpenId);
//        if (cereBuyerUser != null) {
//            cereBuyerUser.setPhone(phone);
//            cereBuyerUser.setUpdateTime(TimeUtils.yyMMddHHmmss());
//            int i = cereBuyerUserDao.updateByPrimaryKeySelective(cereBuyerUser);
//
//            //新增分销员
//            CereShopDistributor cereShopDistributor = new CereShopDistributor();
//            cereShopDistributor.setShopId(shopId);
//            cereShopDistributor.setCreateTime(TimeUtils.yyMMddHHmmss());
//            cereShopDistributor.setDistributorLevelId(grade);
//            cereShopDistributor.setDistributorName(cereBuyerUser.getWechatName());
//            cereShopDistributor.setDistributorPhone(cereBuyerUser.getPhone());
//            cereShopDistributor.setState(IntegerEnum.DISTRIBUTOR_SUCCESS.getCode());
//            cereShopDistributor.setBuyerUserId(cereBuyerUser.getBuyerUserId());
//            //生成10位随机数邀请码
//            cereShopDistributor.setInvitationCode(RandomStringUtil.getRandomCode(10, 0));
//            //默认未清退
//            cereShopDistributor.setIfLiquidation(IntegerEnum.NO.getCode());
//            cereShopDistributorDAO.insertSelective(cereShopDistributor);
//
//            if (i > 0) {
//                return true;
//            } else {
//                return false;
//            }
//        } else {
//            return false;
//        }
        return true;
    }

    @Override
    public Boolean registerVoluntarily(String wechatOpenId, String headImage, String wechatName, String wechatNumber) {
        if (wechatOpenId == null || "".equals(wechatOpenId)) {
            return false;
        }
        if (headImage == null || "".equals(headImage)) {
            return false;
        }
        if (wechatName == null || "".equals(wechatName)) {
            return false;
        }
        if (wechatName == null || "".equals(wechatName)) {
            return false;
        }
        if (wechatNumber == null || "".equals(wechatNumber)) {
            return false;
        }
        //判断是否有这个openid
        List<CereBuyerUser> cereBuyerUser1 = cereBuyerUserDao.getByWxOpenId(wechatOpenId);
        if (cereBuyerUser1 != null) {
            return false;
        }


        //补全初始数据
        CereBuyerUser cereBuyerUser = new CereBuyerUser();
        cereBuyerUser.setWechatOpenId(wechatOpenId);
        cereBuyerUser.setHeadImage(headImage);
        cereBuyerUser.setWechatName(wechatName);
        cereBuyerUser.setWechatNumber(wechatNumber);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        cereBuyerUser.setCreateTime(format);
        cereBuyerUser.setState(true);
        cereBuyerUser.setIfBlack(false);
        cereBuyerUser.setPassword(EncryptUtil.encrypt("000000"));
        cereBuyerUser.setToken(RandomStringUtil.getRandomCode(32, 0));

        //注册之后，还需要注册成分销员
        if (cereBuyerUserDao.insertSelective(cereBuyerUser) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 功能描述: 判断是否关注公众号,如果关注则添加数据
     * @Param: [wechatOpenId]
     * @return: java.lang.Boolean
     * @Author: 况鑫威
     * @Date: 2021/7/12
     * @Time: 14:19
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public synchronized Boolean getUserOpenId(String wechatOpenId) {
        if (wechatOpenId == null || "".equals(wechatOpenId)) {
            return false;
        }
        //获取缓存中的token
        String accessToken = (String) stringRedisService.get(appId + secret + "accessToken");
        Map map = null;
        //没有在查询
        if("".equals(accessToken) || accessToken == null){
            try {
                accessToken = WeixinUtil.getAccessToken(appId, secret);
                stringRedisService.set(appId + secret + "accessToken",accessToken, expire_seconds*1000);
//                accessToken = (String) map.get("access_token");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //用户信息
//        JSONObject jsonObject = GZHUtil.judgeIsFollow((String) map.get("access_token"), wechatOpenId);
        JSONObject jsonObject = GZHUtil.judgeIsFollow(accessToken, wechatOpenId);

        //把缓存中的token保存下来,对比
        String temp = accessToken;
        //判断是否有错误码,有则说明没有调到,则重新调用一次
        if(!WeixinUtil.isTokenFlag(jsonObject)){
            accessToken = WeixinUtil.getAccessToken(appId, secret);
            //如果相等,说明没有更新,直接调用微信的接口
            if(temp.equals(accessToken)){
                accessToken = WeixinUtil.getAccessTokenTwo(appId, secret);
            }
//            accessToken = (String) map.get("access_token");
            stringRedisService.set(appId + secret + "accessToken", accessToken, expire_seconds*1000);
            //刷新数据
            jsonObject = GZHUtil.judgeIsFollow(accessToken, wechatOpenId);
        }

//        try{
            //如果没有添加则保存用户数据
        if(jsonObject.size() != 2 && 1 == jsonObject.getInt("subscribe")){
            List<CereBuyerUser> open = cereBuyerUserDao.getByWxOpenId((String) jsonObject.get("openid"));
            if(open == null){
                CereBuyerUser cereBuyerUser = new CereBuyerUser();
                cereBuyerUser.setWechatOpenId((String) jsonObject.get("openid"));
                cereBuyerUser.setName((String) jsonObject.get("nickname"));
                if((Integer)jsonObject.get("sex") == 1){
                    cereBuyerUser.setSex( "男" );
                }else if((Integer)jsonObject.get("sex") == 2){
                    cereBuyerUser.setSex( "女" );
                }
                cereBuyerUser.setPassword(EncryptUtil.encrypt("123456"));
                cereBuyerUser.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereBuyerUser.setToken(RandomStringUtil.getRandomCode(32, 0));
                cereBuyerUser.setState(true);
                cereBuyerUser.setIfBlack(false);
                //设置默认头像
                cereBuyerUser.setHeadImage((String) jsonObject.get("headimgurl"));
                cereBuyerUserDao.insert(cereBuyerUser);
            }
            return true;
        }else{
            return false;
        }
//        }catch (Exception e){
//            e.printStackTrace();
//            return false;
//        }


//        String json = "{'wechatOpenId':"+s+"}";
//        Gson gson = new Gson();
//        Map<String, Object> map = new HashMap<>();
////        List<CouponBean.DataBean> couponBean = gson.fromJson(wechatOpenId,new TypeToken<List<CouponBean.DataBean>>(){}.getType());
//        map = gson.fromJson(json, map.getClass());
//        CereBuyerUser cereBuyerUser = cereBuyerUserDao.getByWxOpenId((String) map.get("wechatOpenId"));
//        if (cereBuyerUser != null) {
//            return true;
//        } else {
//            return false;
//        }
    }


    @Override
    public MyAccount getMyAccount(Long buyerUserId) {
        MyAccount myAccount = new MyAccount();

        CereBuyerUser cereBuyerUser = cereBuyerUserDao.selectByPrimaryKey(buyerUserId);
        //积分
        Integer point = cerePlatformUserPointDao.selectByPoint(buyerUserId);
//        可提现佣金
//        Integer canWithdraw = cereDistributionOrderDAO.selectByCommission(cereBuyerUser.getPhone(), "1");
        //不按结算条件查询，总佣金   state:不需要计算的订单
        BigDecimal conditionMoney = cereDistributionOrderDAO.selectByCommission(cereBuyerUser.getPhone(), "5");
        if(conditionMoney == null){
            conditionMoney = new BigDecimal(0);
        }
        //查询已提现或审核中金额
        BigDecimal price = cereDistributionOrderDAO.findWithdrawalMoney(buyerUserId);
        //总佣金减去已提现或审核中金额
        conditionMoney = conditionMoney.subtract(price);

//        //查询提现通过的金额
//        List<CereBuyerWithdrawal> cereBuyerWithdrawal =  cereBuyerWithdrawalDAO.selectByBuyerUserId(buyerUserId);
//        for (CereBuyerWithdrawal buyerWithdrawal : cereBuyerWithdrawal) {
//            //总佣金减去已经提现的
//            conditionMoney = conditionMoney.subtract(buyerWithdrawal.getWithdrawalMoney());
//        }

        //卡券
        int count = cereShopOrderDAO.getCouponCount(cereBuyerUser.getPhone());

        myAccount.setPoints(point);
//        myAccount.setCanWithdraw(canWithdraw);
        myAccount.setConditionMoney(conditionMoney);
        myAccount.setCoupon(count);
        return myAccount;
    }

    @Override
    public List<CereShopOrder> getCoupons(Long cereBuyerUserId) {
        List<CereShopOrder> coupons = cereShopOrderDAO.getCoupons(cereBuyerUserId);
        for (CereShopOrder coupon : coupons) {

            Integer sold = cereShopProductMapper.getSoldOut(coupon.getProductId());
//            if (c.getProductNo()!=null&&c.getProductNo()<=0){
//                //总数-剩余==已售
//            int sold = sku.getTotal() - sku.getStockNumber();
            if(sold == null){
                sold = 0;
            }
            coupon.setSoldOut(sold);
        }
        return coupons;
    }

}
